package cn.openea.perpartner.mpwx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.common.log.factory.AsyncFactory;
import cn.openea.perpartner.mpwx.core.WxServiceTemplate;
import cn.openea.perpartner.mpwx.service.IWxMpMsgService;
import cn.openea.perpartner.mpwx.service.IWxMpSyncService;
import cn.openea.perpartner.mpwx.util.WeChatUtil;
import cn.openea.perpartner.system.entity.SysUser;
import cn.openea.perpartner.system.enums.AppletsEnums;
import cn.openea.perpartner.system.service.ISysConfigService;
import cn.openea.perpartner.system.service.ISysUserService;
import cn.openea.perpartner.system.util.ToolsUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author Weird077
 * @description R_SL02_B006:用户关注与取关时处理的接口
 * @date 2022-06-20 22:19
 */
@Service
public class WxMpMsgServiceImpl implements IWxMpMsgService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    /**
     * R_SL02_B007
     */
    @Autowired
    private IWxMpSyncService wxMpSyncService;

    @Autowired
    private WxServiceTemplate wxServiceTemplate;

    private static final String SUBSCRIBE = "subscribe";
    private static final String UNSUBSCRIBE = "unsubscribe";

    @Override
    public String run(HashMap<String, Object> params) throws Exception {
        String event = (String) params.get("event");
        String fromUserName = (String) params.get("fromUserName");
        String toUserName = (String) params.get("toUserName");
        String eventKey = (String) params.get("eventKey");
        // 关注事件
        if (SUBSCRIBE.equalsIgnoreCase(event)) {
            doSubscribe(fromUserName, toUserName, eventKey);
        }
        // 取关事件
        if (UNSUBSCRIBE.equalsIgnoreCase(event)) {
            unsubScribe(fromUserName, toUserName, eventKey);
        }
        return "";
    }

    /**
     * 关注事件
     *
     * @param fromUserName 当前操作者的openid
     * @param toUserName   公众号注册者的openid
     * @param eventKey     事件值，一般是参数的形式
     */
    public void doSubscribe(String fromUserName, String toUserName, String eventKey) {
        try {
            //第1步：查看被邀请人是否已注册
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            String unionId = getUnionId(fromUserName);
            wrapper.eq(SysUser::getUnionid, unionId);
            SysUser user = userService.getOne(wrapper);
            //第2步：发送通知
            String userId = "";
            //没关注公众号，没注册过小程序
            if (BeanUtil.isEmpty(user)) {
                userId = ToolsUtil.autoUserID();
                String remark = "感谢您关注最佳拍档工作平台！在这里，会有很多的拍档一起工作，赶紧加入我们吧！";
                sendMsg(fromUserName,remark);
            }
            //已注册小程序，但未关注公众号
            if(BeanUtil.isNotEmpty(user) && StrUtil.isNotBlank(user.getMyopenid())){
                String remark = "感谢您关注最佳拍档工作平台！在这里，会有很多的拍档一起工作，赶紧加入我们吧！";
                sendMsg(fromUserName,remark);
            }
            if (StrUtil.isBlank(userId)) {
                userId = user.getUserid();
            }
            // 关注公众号时尝试完成关联用户基本信息 fromUserName
            HashMap<String, Object> parms = new HashMap<>();
            parms.put("fromUserName", fromUserName);
            parms.put("userId", userId);
            wxMpSyncService.run(parms);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("关注公众号时尝试完成关联用户基本信息出错");
        }
    }

    /**
     * 取关事件
     *
     * @param fromUserName 操作者的openid
     * @param toUserName   公众号注册者的openid
     * @param eventKey     事件值，一般是参数的形式
     */
    public void unsubScribe(String fromUserName, String toUserName, String eventKey) throws WxErrorException {
        // 这里需要对用户表的状态进行及时的更新
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getMyopenid, fromUserName);
        SysUser user = userService.getOne(wrapper);
        if (BeanUtil.isNotEmpty(user)) {
            user.setIsSubscribed("0");
            userService.saveOrUpdate(user);
            user.setAppletId(AppletsEnums.MEILY.getAppletId());
            userService.updateUserCache(user);
            String url = configService.selectConfigByKey(AppletsEnums.MEILY.getAppletId()+".account.async.url");
            if(StrUtil.isNotBlank(url)){
                JSONObject wxObject = new JSONObject();
                wxObject.put("userid",user.getUserid());
                wxObject.put("nickname",user.getNickname());
                wxObject.put("avatar",user.getNickname());
                wxObject.put("subscriptionOpenid",user.getMyopenid());
                wxObject.put("stepStatus",user.getStepstatus());
                wxObject.put("unionid",user.getUnionid());
                wxObject.put("isSubscribed",user.getIsSubscribed());
                BeanUtil.copyProperties(user,wxObject,false);
                AsyncManager.me().execute(AsyncFactory.asyncBpmOrg(url,wxObject));
            }
        }
    }
    @Override
    public String getUnionId(String wxmpopenid) throws WxErrorException {
        WxMpService wxMpService = wxServiceTemplate.getWxMpService();
        // 获取用户基本信息
        WxMpUser wxMpUser = wxMpService.userInfo(wxmpopenid, null);
        return wxMpUser.getUnionId();
    }

    /**
     * 给用户增加积分，以及发送消息通知
     * @param sendTo 微信id
     * @throws Exception
     */
    private void sendMsg(String sendTo,String remark) {


        WeChatUtil.sendTextMsg(sendTo, sendTo,remark);
    }
}
